package io.github.starwishsama.comet.utils

import cn.hutool.core.util.URLUtil
import com.google.gson.JsonParser
import io.github.starwishsama.comet.BotVariables
import io.github.starwishsama.comet.objects.pojo.Ascii2dPicSearchResult
import io.github.starwishsama.comet.objects.pojo.PicSearchResult
import org.jsoup.Jsoup

object PictureSearchUtil {
    private const val sauceNaoApi = "https://saucenao.com/search.php?db=5&output_type=2&numres=3&url="
    private const val ascii2d = "https://ascii2d.net/search/url/"

    fun sauceNaoSearch(url: String): PicSearchResult {
        val encodedUrl = URLUtil.encode(url)
        val key = BotVariables.cfg.saucenaoApiKey
        val request = NetUtil.doHttpRequestGet(
            "$sauceNaoApi$encodedUrl${if (key != null && key.isNotEmpty()) "&api_key=$key" else ""}",
            5000
        )
        val result = request.executeAsync()

        if (result.isOk && result.header("Content-Type").contains("json")) {
            val body = result.body()
            try {
                val resultBody = JsonParser.parseString(body)
                if (resultBody.isJsonObject) {
                    val resultJson = resultBody.asJsonObject["results"].asJsonArray[0].asJsonObject
                    val similarity = resultJson["header"].asJsonObject["similarity"].asDouble
                    val pictureUrl = resultJson["header"].asJsonObject["thumbnail"].asString
                    val originalUrl = resultJson["data"].asJsonObject["ext_urls"].asJsonArray[0].asString
                    val title = resultJson["data"].asJsonObject["title"].asString
                    val author =  resultJson["data"].asJsonObject["member_name"].asString
                    if(!resultJson["data"].asJsonObject["member_id"].isJsonNull){
                        val uid = resultJson["data"].asJsonObject["member_id"].asString
                        return PicSearchResult(pictureUrl, originalUrl, similarity, title, author, uid)
                    }
                    return PicSearchResult(pictureUrl, originalUrl, similarity, title, author, "")
                }
            } catch (e: Exception) {
                BotVariables.logger.error("[以图搜图] 在解析 API 传回的 json 时出现了问题", e)
                FileUtil.createErrorReportFile("picsearch", e, body, request.url)
            }
        }
        return PicSearchResult.emptyResult()
    }

    fun ascii2dSearch(url: String): Ascii2dPicSearchResult {
        val baseURL = "https://ascii2d.net"
        val colorRequest = Jsoup.connect("$ascii2d$url")
        colorRequest.header("user-agent", NetUtil.defaultUA).followRedirects(true)
            .proxy(BotVariables.cfg.proxyUrl, BotVariables.cfg.proxyPort)
        println("$ascii2d$url")

        val colorHtml = colorRequest.get()
        val colorElements = colorHtml.body().getElementsByClass("container")
        val colorUrl: String
        val colorSources = colorElements.select(".info-box")[1].select("a")
        val colorUsers: String
        val colorOrig: String

        val bovwReqSources = colorElements.select(".p-d-1")[0]
        val bovwReqElement = bovwReqSources.select("a")
        val bovwReqUrl= baseURL + bovwReqElement[1].attributes()["href"]
        val bovwRequest = Jsoup.connect(bovwReqUrl)
        bovwRequest.header("user-agent", NetUtil.defaultUA).followRedirects(true)
                .proxy(BotVariables.cfg.proxyUrl, BotVariables.cfg.proxyPort)
        println(bovwReqUrl)
        val bovwHtml = bovwRequest.get()
        val bovwElements = bovwHtml.body().getElementsByClass("container")
        val bovwSources = bovwElements.select(".info-box")[1].select("a")
        val bovwUrl: String
        val bovwUsers: String
        val bovwOrig: String
        try {
            colorUrl = baseURL + colorElements.select(".image-box")[1].select("img")[0].attributes()["src"]
            colorOrig = colorSources[0].attributes()["href"]
            colorUsers = colorSources[1].attributes()["href"]
            println(colorUsers)
            bovwUrl = baseURL + bovwElements.select(".image-box")[1].select("img")[0].attributes()["src"]
            bovwOrig = bovwSources[0].attributes()["href"]
            bovwUsers = bovwSources[1].attributes()["href"]
            println(bovwUsers)
        } catch (ignored: IndexOutOfBoundsException) {
            return Ascii2dPicSearchResult.emptyResult()
        }
        return Ascii2dPicSearchResult(colorUrl, colorOrig, colorUsers, bovwUrl, bovwOrig, bovwUsers)
    }
}